import { Component, Injector, OnInit, SimpleChanges, OnChanges, Input } from '@angular/core';
import { HDPatrolFormListDto, HDPatrolFormServiceProxy } from '@shared/service-proxies/service-proxies';
import { SelectBaseComponent } from '../../../../commmon/components/select.components.base';
import { CustomFormGroup } from '../../custom-form.type';
import { CustomFormEditorGroupComponent } from '../custom-form-editor-group.component';

@Component({
    selector: 'app-patrol-form-select',
    templateUrl: './patrol-form-select.component.html',
    styles: []
})
export class PatrolFormSelectComponent extends SelectBaseComponent<HDPatrolFormListDto> implements OnInit, OnChanges {

    @Input() patrolTypeId: number;
    protected getEntityVal(entity: HDPatrolFormListDto) {
        return entity ? entity.name : undefined;
    }
    protected getEntityById(id: string | number): HDPatrolFormListDto {
        return this.dataList.find(f => f.id === id);
    }
    protected getEntityId(entity: HDPatrolFormListDto): string | number {
        return entity ? entity.id : 0;
    }

    constructor(injector: Injector, private _hDPatrolFormService: HDPatrolFormServiceProxy) { super(injector); }

    ngOnInit() {
        this.getList();
    }
    getList(filterText?: string) {
        if (this.patrolTypeId === 0) {
            this.patrolTypeId = undefined;
        }
        this.loadingService.showLoading = true;
        this._hDPatrolFormService.getPaged(this.patrolTypeId, filterText, 'name', 999, 0).subscribe(result => {
            this.setDataList(result.items);
        });
    }
    previewForm(item: HDPatrolFormListDto, e: MouseEvent) {
        e.stopPropagation();
        this._hDPatrolFormService.getForEdit(item.id).subscribe(result => {
            this.modalHelper.static(CustomFormEditorGroupComponent, {
                formJson: CustomFormGroup.fromJson(JSON.parse(result.hdPatrolForm.formJson)),
                isEditor: false
            }).subscribe(() => { });
        });
    }
    ngOnChanges(changes: SimpleChanges) {
        super.ngOnChanges(changes);
        if (this.hasChange('patrolTypeId', changes)) {
            this.patrolTypeId = changes.patrolTypeId.currentValue;
            this.selected = undefined;
            this.getList();
        }
    }
}
